package com.atguigu.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.gulimall.search.config.EsConfig;
import com.atguigu.gulimall.search.constant.EsContant;
import com.atguigu.gulimall.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author weichen
 * @email 519543138@qq.com
 * @date 2022-09-20 下午10:46
 */
@Slf4j
@Service
public class ProductSaveServiceImpl implements ProductSaveService {
    @Autowired
    RestHighLevelClient restHighLevelClient;
    @Override
    public Boolean productStatusUp(List<SkuEsModel> models) throws IOException {
        //1、在kibana中创建索引product,映射关系

        //2、es中保存数据
        //BulkRequest bulkRequest, RequestOptions options
        BulkRequest bulkRequest=new BulkRequest();
        for (SkuEsModel esModel: models) {
            IndexRequest index=new IndexRequest(EsContant.PRODUCT_INDEX);
            index.id(esModel.getSkuId().toString());
            index.source(JSON.toJSONString(esModel), XContentType.JSON);
            bulkRequest.add(index);
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, EsConfig.COMMON_OPTIONS);

        //TODO 1、如果批量错误
        boolean b = bulk.hasFailures();
        if(b){
            log.error("商品上架ES返回错误:{}",bulk.buildFailureMessage());
            System.out.println(bulk.buildFailureMessage());
        }else{
            List<String> collect = Arrays.stream(bulk.getItems()).map(bulkItem -> {
                return bulkItem.getId();
            }).collect(Collectors.toList());
            log.info("商品上架ES完成:{}",collect);
        }

        return b;
    }
}
